<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class SearchController extends Controller
{
    public function index(Request $request)
    {
    	 $where = [];
        //实例化要操作的表
        $db = DB::table('product')
        ->join('type','product.path_id','=','type.id')
        ->select('product.*', 'type.name as typename');
        
        // dd($db);
        // dd($db);
        //判断有没有搜索name字段的值
        // dd();
        if($request->has('name')){
        //     // 获取要搜索的name字段的值
            $name = $request->input('name');
        //     //添加where模糊匹配条件
            $db->where('product.name','like',"%{$name}%")->orderBy('product.path_id');
            $where['name'] = $name;
        }
        // 分页
        // dd($list);
        $list = $db->paginate(6);
         //类别
         $type=DB::table('type')->get()->all();
         $type1=DB::table('type')->inRandomOrder()->take(8)->get()->all();
        // 搜索关键字
         $ss=DB::table('product')->inRandomOrder()->take(6)->get()->all();
         //链接
         $links=DB::table('links')->get();

        //推荐
        $rec = DB::table('recommend')
        ->join('product', 'product.id', '=', 'recommend.product_id')
        ->select('recommend.*', 'product.name', 'product.keywords', 'product.picture', 'product.lower_price', 'product.fixed_price')
        ->orderBy(\DB::raw('RAND()'))
        ->take(2)
        ->get();
        // dd($rec);

        // dd($list);
        // $list = $db->get();
        //加载模板
        $count=count($list);
        return view('home.search',['list'=>$list, 
            'count'=>$count,
            'search'=>$ss,
         'all'=>$type,
         'sall'=>$type1,
         'rec'=>$rec,
         'links'=>$links,
         'where'=>$where]);
    }
    public function typeindex($id)
    {
       
       
         $db= DB::table('product')
        
        ->join('type','product.path_id','=','type.id')
        ->select('product.*', 'type.name as typename')
        ->where('type.id',$id);
           
        
        $list=$db->paginate(6);


         $type=DB::table('type')->get()->all();
           $type1=DB::table('type')->inRandomOrder()->take(8)->get()->all();
            // 搜索关键字
         $ss=DB::table('product')->inRandomOrder()->take(8)->get()->all();
             //链接
         $count=count($list);
         $rec = DB::table('recommend')
        ->join('product', 'product.id', '=', 'recommend.product_id')
        ->select('recommend.*', 'product.name', 'product.keywords', 'product.picture', 'product.lower_price', 'product.fixed_price')
        ->orderBy(\DB::raw('RAND()'))
        ->take(2)
        ->get();
        // dd($rec);
         // dd($db);
         $links=DB::table('links')->get();
          return view('home.search',['list'=>$list, 
            'count'=>$count,
            'search'=>$ss,
         'all'=>$type,
         'rec'=>$rec,
         'sall'=>$type1,
         'links'=>$links,
         ]);
    }
}
